package com.loong.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.loong.framework.constant.SystemConst;
import com.loong.framework.utils.CommonUtil;
import com.loong.framework.utils.SystemUtil;
import com.loong.system.dto.TenantInfoPageDTO;
import com.loong.system.dto.TenantPageDTO;
import com.loong.system.entity.Tenant;
import com.loong.system.mapper.MenuMapper;
import com.loong.system.mapper.TenantMapper;
import com.loong.system.mapper.UserMapper;
import com.loong.system.service.ITenantService;
import com.loong.system.service.IUserService;
import com.loong.system.vo.TenantShowListVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 47349
 * @description 针对表【sys_tenant(租户表)】的数据库操作Service实现
 * @createDate 2024-04-01 22:45:44
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

  @Resource private IUserService userService;
  @Resource private TenantMapper tenantMapper;
  @Resource private UserMapper userMapper;
  @Resource private MenuMapper menuMapper;

  @Override
  public Page<Tenant> pageTenantList(TenantPageDTO tenantPageDTO) {
    String name = tenantPageDTO.getName();
    String contactNumber = tenantPageDTO.getContactNumber();
    String tenantId = tenantPageDTO.getTenantId();

    Page<Tenant> page = SystemUtil.buildPageFromDTO(tenantPageDTO, Tenant.class);

    return this.lambdaQuery()
        .eq(CommonUtil.notNullOrEmpty(tenantId), Tenant::getId, tenantId)
        .like(CommonUtil.notNullOrEmpty(name), Tenant::getName, name)
        .like(CommonUtil.notNullOrEmpty(contactNumber), Tenant::getContactNumber, contactNumber)
        .page(page);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void addTenant(Tenant tenant) {
    this.save(tenant);

    // 创建对应的租户管理员
    userService.addTenantUser(
        tenant.getContactNumber(), tenant.getName(), SystemConst.DefaultPassword, tenant.getId());
  }

  @Override
  public Page<TenantShowListVO> pageTenantShowList(TenantInfoPageDTO tenantInfoPageDTO) {
    //    List<TenantShowListVO> vos = tenantMapper.pageTenantAppList(tenantInfoPageDTO);
//    List<Menu> all = menuMapper.all();
    return null;
  }
}
